#include"StdAfx.h"

pgInputEventManager::pgInputEventManager()
{
	m_nButtonStates = 0;
}

pgInputEventManager::~pgInputEventManager()
{
}

void pgInputEventManager::ShutDown()
{
}

void pgInputEventManager::Update(float frameTime)
{
}

void pgInputEventManager::RegisterListener(IEventListener* listener, EVENT_CLASS eventClass, EVENT_NAME eventName)
{
	if (listener)
		m_listeners.push_back(listener);
	else
		PG_LOG_WARNING_EX(TOPIC_INPUT_EVENT_MANAGER, "Trying to register a null listener!");
}

void pgInputEventManager::UnregisterListener(IEventListener* listener)
{
	if (!listener)
	{
		PG_LOG_WARNING_EX(TOPIC_INPUT_EVENT_MANAGER, "Trying to unregister a null listener!");
		return;
	}

	std::list<IEventListener*>::iterator iter = m_listeners.begin();
	bool bFound = false;
	while(iter != m_listeners.end())
	{
		if (listener->id == (*iter)->id)
		{
			bFound = true;
			break;
		}
		++iter;
	}

	if (bFound)
		m_listeners.remove((*iter));
	else
		PG_LOG_WARNING_EX(TOPIC_INPUT_EVENT_MANAGER, "Couldn't find listener: %d for unregistering!", listener->id);
}

void pgInputEventManager::RegisterEvent(int eventName, int eventClass, IEventData *pData)
{
	// eventname is the id of the windows key
	// Check if key is mapped
	if (m_keyMaps.find(eventName) == m_keyMaps.end())
		return;

	if (eventClass == eKPEC_press)
	{
		KeyPressed(m_keyMaps[eventName]);
	}
	else
	{
		KeyReleased(m_keyMaps[eventName]);
	}

	DispatchEvents(m_keyMaps[eventName], eventClass);
}

void pgInputEventManager::KeyPressed(unsigned int id)
{
	m_nButtonStates |= id;
}

void pgInputEventManager::KeyReleased(unsigned int id)
{
	m_nButtonStates &= ~id;
}

bool pgInputEventManager::IsKeyPressed(unsigned int id)
{
	if (m_nButtonStates & id)
		return true;
	else
		return false;
}

void pgInputEventManager::MapKey(BYTE virtualKey, unsigned int pgKey)
{
	// Map the windows key to a PaleGemKey

	// Don't map keys twice
	if (m_keyMaps.find(virtualKey) != m_keyMaps.end())
	{
		PG_LOG_WARNING_EX(TOPIC_INPUT_EVENT_MANAGER, "Trying to mapp a already mapped key (id %d) !", virtualKey);
	}

	m_keyMaps[virtualKey] = pgKey;
}

void pgInputEventManager::DispatchEvents(unsigned int pgKey, int activationMode)
{
	std::list<IEventListener*>::iterator it;

	IEvent *pEvent = new IEvent();

	pEvent->eventId = pgKey;
	pEvent->eventClass = activationMode;
	pEvent->pData = NULL;


	for (it = m_listeners.begin(); it != m_listeners.end(); ++it)
	{
		(*it)->OnEvent(pEvent);
	}

	PG_SAFE_DELETE(pEvent);
}

bool pgInputEventManager::IsKeyTapped(unsigned int id)
{
	if (IsKeyPressed(id))
	{
		KeyReleased(id);
		return true;
	}
	else
	{
		return false;
	}
}